// 视图
import view from '@src/views/adv';

// 列表组件
import advListConponent from '@src/components/advList.ejs'
import pageConponent from '@src/components/page.ejs'

// 提示工具
import toastr from 'toastr';

// api
import * as advApi from '@src/api/adv'

export default (req, res, next) => {
  res.render(view());

  // 渲染
  render();

  // 打开新增表单
  document.querySelector("#addAdvBtn").addEventListener('click', () => openFrom({
    modalTitle: "添加广告"
  }))

  // 打开编辑表单
  document.querySelector("#advTable").addEventListener('click', async ({ target }) => {
    if (!target.classList.contains('btn-edit')) {
      return;
    }

    const { data } = await advApi.get(target.dataset.id);
    openFrom({
      id: data._id,
      modalTitle: "修改广告",
      title: data.advTitle,
      type: data.advType,
      href: data.advHref,
      order: data.orderNum,
      src: data.advPic,
    })
  })

  // 图片预览
  document.addAdvForm.advPic.addEventListener('change', imgPreview);

  // 表单提交
  document.addAdvForm.addEventListener('submit', handleSubmit);

  // 翻页
  document.querySelector("#advTable").addEventListener('click', handlePage)

  // 搜索
  document.querySelector("#searchAdv").addEventListener('click', () => render())


}

function openFrom(data) {
  // modalTitle, title, type, order, fileName, src
  const modalTitleE = document.querySelector('#modalTitle');
  const advTitleE = document.querySelector('#advTitle');
  const advTypeE = document.querySelector(`#advType`);
  const advHrefE = document.querySelector('#advHref');
  const orderNumE = document.querySelector('#orderNum');
  const preImgE = document.querySelector('#preImg');
  const advSaveE = document.querySelector('#adv-save');


  advSaveE.dataset.id = data.id || '';
  modalTitleE.innerHTML = data.modalTitle;
  advTitleE.value = data.title || '';
  advTypeE.value = data.type || 1;
  advHrefE.value = data.href || '';
  orderNumE.value = data.order || 100;
  if (data.src) {
    preImgE.src = "/server/" + data.src;
    preImgE.style.display = 'block';
  } else {
    preImgE.style.display = 'none';
  }

  $("#advModal").modal('show')
}

function handlePage({ target }) {

  if (!target.classList.contains('page-link')) {
    return;
  }


  render(target.dataset.i)
}

async function render(pageNo = 1, pageSize = 3) {
  const res = await advApi.page({
    pageNo,
    pageSize,
    keyword: document.querySelector('#keyword').value.trim(),
  });
  document.querySelector("#advTable").innerHTML = advListConponent({
    list: res.data,
    typeMap: {
      1: '轮播图广告',
      2: '轮播图底部广告',
      3: '热门回收广告',
      4: '优品精选广告',
    },
  }) + pageConponent({
    id: "advListPage",
    pageNo: res.pageNo,
    pageSum: res.pageSum
  })
}

function cancelPreview() {
  const preImgTag = document.querySelector('#preImg');
  preImgTag.src = '';
  preImgTag.style.display = 'none';
}

function imgPreview() {
  const file = this.files[0];
  const preImgTag = document.querySelector('#preImg');
  if (!file) {
    cancelPreview()
    return;
  }
  // 实例化 FilerReader
  const fileReader = new FileReader();
  fileReader.readAsDataURL(file);
  fileReader.onloadend = () => {

    preImgTag.src = fileReader.result;
    preImgTag.style.display = 'block';
  };

}

async function handleSubmit(event) {
  event.preventDefault();


  const title = document.addAdvForm.title.value.trim();
  const type = document.addAdvForm.type.value.trim();
  const href = document.addAdvForm.href.value.trim();
  const order = document.addAdvForm.order.value.trim();
  const pic = document.addAdvForm.pic;

  if (!title) {
    toastr.error('请填写标题');
    return;
  }

  if (!type) {
    toastr.error('请填写类别');
    return;
  }
  if (!href) {
    toastr.error('请填写链接');
    return;
  }
  if (!/^\d+$/.test(order)) {
    toastr.error('请按规范填写排序');
    return;
  }

  if (!pic || !pic.files[0]?.size) {
    toastr.error('请上传图片');
    return;
  }

  const formData = new FormData();
  formData.append('advTitle', title);
  formData.append('advType', type);
  formData.append('advHref', href);
  formData.append('orderNum', order);
  formData.append('advPic', pic.files[0]);

  const id = document.querySelector("#adv-save").dataset.id;
  if (id) {
    formData.append('id', id);
    await advApi.edit(formData);
    toastr.success('编辑广告成功')
  } else {
    await advApi.add(formData);
    toastr.success('新增广告成功');
  }

  $('#advModal').modal('hide');
  document.addAdvForm.reset();
  cancelPreview();

  render()
}
